package cn.hdu.charge.dao;

import cn.hdu.charge.domain.Record;
import cn.hdu.charge.domain.User;
import cn.hdu.utils.commons.CommonUtils;
import cn.hdu.utils.jdbc.TxQueryRunner;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class RecordDao {
    private QueryRunner qr = new TxQueryRunner();

    public boolean addRecord(Record record) throws SQLException {
        String sql = "insert into record(recordId,userId,deviceId,start,price,duration,status) values(?,?,?,?,?,?,?)";
        Object[] params = {record.getRecordId(),
                record.getUser().getUserId(), record.getDeviceId(),
                record.getStart(), record.getPrice(),
                record.getDuration(), record.getStatus()};
        return qr.update(sql, params) > 0;
    }

    public boolean updateStatus(String recordId) throws SQLException {
        String sql = "update record set status=? where recordId=?";
        Object[] params = {1, recordId};
        int updated = qr.update(sql, params);
        return updated > 0;
    }

    public List<Record> getRecord(User user) throws SQLException {
        String sql = "SELECT FROM record WHERE userId=?";
        List<Map<String, Object>> mapList = qr.query(sql, new MapListHandler(), user.getUserId());
        List<Record> recordList = toRecordList(mapList);
        return recordList;
    }

    private List<Record> toRecordList(List<Map<String, Object>> mapList) {
        List<Record> recordList = new ArrayList<>();
        for(Map<String, Object> map : mapList) {
            Record record = toRecord(map);
            recordList.add(record);
        }
        return recordList;
    }

    private Record toRecord(Map<String, Object> map) {
        Record record = CommonUtils.toBean(map, Record.class);
        User user = CommonUtils.toBean(map, User.class);
        record.setUser(user);
        return record;
    }

}
